/**
 * 
 */
package br.embedded.socialapp.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.embedded.socialapp.business.UserManager;
import br.embedded.socialapp.exceptions.UserException;

/**
 * @author daniel
 *
 */
@SuppressWarnings("serial")
public class RegisterServlet extends HttpServlet
{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		register(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		register(req, resp);
	}

	private void register(HttpServletRequest req, HttpServletResponse resp)
	{
		boolean result = false;
		
		String login = req.getParameter("login");
		String id = req.getParameter("id");
		String network = req.getParameter("network");
		
		String[] params = {login, id, network};
		
		if (validateParameters(params))
		{
			try {
				network = network.replace(".com", "").trim();
				
				if (network.equals("myspace"))
					id = id.replace("myspace.com:", "").trim();
					
				UserManager.getInstance().updateSocialNetworkId(login, network, id);
				result = true;
			} catch (UserException e) {
				e.printStackTrace();
			}
		}
		writeResponse(resp, result);
	}
	
	private boolean validateParameters(String[] params)
	{
		for (String param : params) {
			if (param == null || param.isEmpty())
				return false;
		}
		return true;
	}
	
	private void writeResponse(HttpServletResponse resp, boolean result)
	{
		resp.setContentType("text/html");
		PrintWriter writer;
		try {
			writer = resp.getWriter();
			writer.append("<html>");
			writer.append("<body>");
		
			if (result)
				writer.append("OK");
			else
				writer.append("ERROR");
		
			writer.append("</body>");
			writer.append("</html>");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
